from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from datetime import datetime
from backend.database import SessionLocal
from backend.models import Resource, User
from backend.schemas import ResourceCreate, ResourceResponse
import logging

# 设置日志记录
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 路由前缀保持空
router = APIRouter(prefix="")

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# 获取资源列表
@router.get("/api/resources", response_model=List[ResourceResponse])
async def list_resources(db: Session = Depends(get_db)):
    """
    获取所有资源，按上传时间降序
    """
    resources = db.query(Resource).order_by(Resource.upload_time.desc()).all()
    return resources

# 创建新资源
@router.post("/api/resources", response_model=ResourceResponse)
async def create_resource(resource: ResourceCreate, db: Session = Depends(get_db)):
    """
    上传新资源，需要提供 uploader_id
    """
    uploader = db.query(User).filter(User.user_id == resource.uploader_id).first()
    if not uploader:
        logger.warning(f"用户不存在: uploader_id={resource.uploader_id}")
        raise HTTPException(status_code=404, detail="用户不存在")
    db_res = Resource(
        title=resource.title,
        content=resource.content,
        category=resource.category,
        uploader_id=resource.uploader_id,
        upload_time=datetime.utcnow(),
        view_count=0
    )
    db.add(db_res)
    db.commit()
    db.refresh(db_res)
    logger.info(f"成功上传资源: resource_id={db_res.resource_id}")
    return db_res

# 删除资源
@router.delete("/api/resources/{resource_id}")
async def delete_resource(resource_id: int, user_id: int = Query(...), db: Session = Depends(get_db)):
    """
    删除资源，只允许上传者删除
    """
    db_res = db.query(Resource).filter(Resource.resource_id == resource_id).first()
    if not db_res:
        raise HTTPException(status_code=404, detail="资源不存在")
    if db_res.uploader_id != user_id:
        raise HTTPException(status_code=403, detail="无权限删除此资源")
    db.delete(db_res)
    db.commit()
    return {"message": "资源已删除"} 